package org.bitmaps.cutBitmap.tool
{
	import flash.display.DisplayObjectContainer;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.geom.Rectangle;

	public class DrawRect extends Sprite
	{
		public static const DRAW_START:String = "draw_start";
		public static const DRAW_COMPLETE:String = "draw_complete";
		
		private var _bound:Rectangle;
		protected var _graphics:Sprite;
		protected var _startPoint:Point;
		protected var _endPoint:Point;
		public var color:uint=0;
		
		public var type:uint = 1;
		/**
		 * 在规定矩阵内绘制
		 * @param $bound
		 */
		public function DrawRect($bound:Rectangle)
		{
			type = 1;
			_bound = $bound;
			_graphics = new Sprite();
			this.addChild(_graphics);
			this.addEventListener(Event.ADDED_TO_STAGE,addToStage);
		}
		
		private function addToStage(e:Event):void
		{
			this.removeEventListener(Event.ADDED_TO_STAGE,addToStage);
			
			stage.addEventListener(MouseEvent.MOUSE_DOWN,stageDown);
		}
		
		protected function stageDown(e:MouseEvent):void
		{
			if(!_bound.contains(e.stageX,e.stageY))
			{
				return;
			}
			stage.addEventListener(MouseEvent.MOUSE_MOVE,stageMove);
			stage.addEventListener(MouseEvent.MOUSE_UP,stageUp);
			_startPoint = this.globalToLocal(new Point(e.stageX,e.stageY));
			dispatchEvent(new Event(DRAW_START));
		}
		
		protected function stageMove(e:MouseEvent):void
		{
			if(!_bound.contains(e.stageX,e.stageY))
			{
				return;
			}
			endPoint = this.globalToLocal(new Point(e.stageX,e.stageY));
			draw();
		}
		
		protected function stageUp(e:MouseEvent):void
		{
			if(!_bound.contains(e.stageX,e.stageY))
			{
				return;
			}
			
			stage.removeEventListener(MouseEvent.MOUSE_MOVE,stageMove);
			stage.removeEventListener(MouseEvent.MOUSE_UP,stageUp);
			if(_endPoint)
			{
				stage.removeEventListener(MouseEvent.MOUSE_DOWN,stageDown);
				dispatchEvent(new Event(DRAW_COMPLETE));
			}
		}
		
		public function set startPoint(p:Point):void
		{
			_startPoint = p;
		}
		
		public function set endPoint(p:Point):void
		{
			_endPoint = p;
		}
		
		protected function draw():void
		{
			_graphics.graphics.clear();
			_graphics.graphics.lineStyle(1,color);
			_graphics.graphics.drawRect(_startPoint.x,_startPoint.y,_endPoint.x-_startPoint.x,_endPoint.y-_startPoint.y);
		}
		
		public function destroy():void
		{
			stage.removeEventListener(MouseEvent.MOUSE_DOWN,stageDown);
			stage.removeEventListener(MouseEvent.MOUSE_MOVE,stageMove);
			stage.removeEventListener(MouseEvent.MOUSE_UP,stageUp);
			this.removeEventListener(Event.ADDED_TO_STAGE,addToStage);
			if(parent)
			{
				_graphics.graphics.clear();
				parent.removeChild(this);
			}
		}
	}
}